import { UserType, AuthFormType } from "types";

const apiUrl = process.env.REACT_APP_API_URL;
const localStorageKey = "__auth__provider_token__";

export const getToken = () => window.localStorage.getItem(localStorageKey);

export const handleUserResponse = ({ user }: { user: UserType }) => {
  window.localStorage.setItem(localStorageKey, user.token || "");
  return user;
};

export const login = (data: AuthFormType) => {
  const config = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  };

  return fetch(`${apiUrl}/login`, config).then(async (res) => {
    const result = await res.json();
    if (res.ok) {
      return handleUserResponse(result);
    }

    return Promise.reject(result);
  });
};

export const register = (data: AuthFormType) => {
  const config = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  };

  return fetch(`${apiUrl}/register`, config).then(async (res) => {
    const result = await res.json();
    if (res.ok) {
      return handleUserResponse(result);
    }

    return Promise.reject(result);
  });
};

export const logout = async () => {
  window.localStorage.removeItem(localStorageKey);
};
